<?php
declare (strict_types=1);

namespace app\common\library\wechat;

use GuzzleHttp\Client;
use QL\QueryList;
use QL\Ext\PhantomJs;

class Crawler
{
    protected $client;

    protected $token;
    protected $cookie;

    protected $errorCode;
    protected $errorMsg;

    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * 根据名称搜索公众号 - （微信公众号：找回账号接口）
     * @param string $query 公众号名称
     * @param integer $begin 开始节点
     * @return boolean|array
     */
    public function getAccountListByCommon($query, $begin = 0)
    {
        $url = "https://mp.weixin.qq.com/acct/findacct?action=search";

        $res = $this->client->request('post', $url, [
            'headers' => [
                'origin' => 'https://mp.weixin.qq.com',
                'referer' => 'https://mp.weixin.qq.com/acct/findacct?action=scan&token=&lang=zh_CN',
            ],
            'form_params' => [
                'token' => '',
                'lang' => ' zh_CN',
                'f' => ' json',
                'ajax' => 1,
                //'random' => 0.956958638819519,
                'begin' => $begin,
                'count' => 5,
                'query' => $query,
                'acct_type' => 0
            ],
        ]);
        $json = (string)$res->getBody();

        return $this->responseResult($json);
    }

    /**
     * 根据名称搜索公众号 - （微信公众号：文章-超链接-选择公众号）
     * @param string $query 公众号名称
     * @param integer $begin 开始节点
     * @return boolean|array
     */
    public function getAccountListBySelf($query, $begin = 0)
    {
        $url = "https://mp.weixin.qq.com/cgi-bin/searchbiz?action=search_biz&begin={$begin}&count=5&query={$query}&token={$this->token}&lang=zh_CN&f=json&ajax=1";
        $res = $this->client->request('GET', $url, [
            'headers' => [
                'origin' => 'https://mp.weixin.qq.com',
                'referer' => "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=77&token={$this->token}&lang=zh_CN",
                'Cookie' => $this->cookie
            ],
        ]);
        $json = (string)$res->getBody();

        return $this->responseResult($json);
    }

    /**
     * 根据公众号id获取文章 - （微信公众号：文章-超链接-选择公众号）
     * @param string $fakeid 公众号id
     * @param integer $begin 开始节点
     * @param string $query 文章关键词
     * @return boolean|array
     */
    public function getAccountAppMsg($fakeid, $begin = 0, $query = '')
    {
        $url = "https://mp.weixin.qq.com/cgi-bin/appmsg?action=list_ex&begin={$begin}&count=5&fakeid={$fakeid}&type=9&query={$query}&token={$this->token}&lang=zh_CN&f=json&ajax=1";
        $res = $this->client->request('GET', $url, [
            'headers' => [
                'origin' => 'https://mp.weixin.qq.com',
                'referer' => "https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_edit_v2&action=edit&isNew=1&type=77&token={$this->token}&lang=zh_CN",
                'Cookie' => $this->cookie
            ],
        ]);
        $json = (string)$res->getBody();

        $search = json_decode($json, true);

        if ($search['base_resp']['ret'] !== 0) {
            $this->errorCode = $search['base_resp']['ret'];
            $this->errorMsg = $search['base_resp']['err_msg'];
            return false;
        }
        if (isset($search['app_msg_list'])) {
            $result = [
                $search['app_msg_cnt'],
                $search['app_msg_list'],
            ];
        } else {
            $result = false;
        }

        return $result;
    }

    /**
     * 获取公众号文章的内容
     * @param string $url 文章链接
     * @param false $async 是否异步
     * @return string
     */
    public function getMsgContent($url, $async = false)
    {
        if ($async) {
            $ql = QueryList::getInstance();
            $this->os = PHP_OS == 'Linux' ? 'linux' : 'windows';
            if ($this->os == 'linux') {
                $path = app()->getRootPath() . 'phantomjs/linux/phantomjs';
                $ql->use(PhantomJs::class, $path);
            }
            if ($this->os == 'windows') {
                $path = app()->getRootPath() . 'phantomjs/windows/phantomjs.exe';
                $ql->use(PhantomJs::class, $path);
            }
            $html = $ql->browser($url)->getHtml();
        } else {
            $res = $this->client->request('GET', $url);
            $html = (string)$res->getBody();
        }
        return $html;
    }

    /**
     * 响应结果
     * @return boolean|array
     */
    protected function responseResult($json)
    {
        $search = json_decode($json, true);

        if ($search['base_resp']['ret'] !== 0) {
            $this->errorCode = $search['base_resp']['ret'];
            $this->errorMsg = $search['base_resp']['err_msg'];
            return false;
        }
        if (isset($search['list'])) {
            $result = $search['list'];
        } else {
            $result = false;
        }

        return $result;
    }

    /**
     * @param mixed $token
     */
    public function setToken($token): void
    {
        $this->token = $token;
    }

    /**
     * @param mixed $cookie
     */
    public function setCookie($cookie): void
    {
        $this->cookie = $cookie;
    }

    /**
     * @return mixed
     */
    public function getErrorCode()
    {
        //200003 - invalid session - cookie失效
        //200013 - freq control - 频率控制
        //200040 - invalid csrf token - token失效

        return $this->errorCode;
    }

    /**
     * @return mixed
     */
    public function getErrorMsg()
    {
        return $this->errorMsg;
    }
}